package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.User;
import cn.lijinquan.p2p.entites.UserAcount;
import com.lijinquan.springcloud.service.RedisService;
import com.lijinquan.springcloud.service.UserAcountService;
import com.lijinquan.springcloud.service.UserService;
import com.lijinquan.springcloud.utils.ImageUtil;
import com.lijinquan.springcloud.utils.MD5Util;
import com.lijinquan.springcloud.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lijinquan on 2019/9/6.
 */
@RestController
public class UserController {

    @Autowired
    RedisService redisService;

    @Autowired
    UserService userService;

    @Autowired
    UserAcountService userAcountService;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/user/uuid")
    public String getUuid() {
        String uuid = null;
        try {
            uuid = UUID.randomUUID().toString();
            logger.info("======>created uuid=" + uuid);
            redisService.set(uuid, uuid);
            redisService.expire(uuid, 3 * 60);
            logger.info("=======>Save key=" + uuid + " value=" + uuid + " expire 3 minuts！");
        } catch (Exception e) {
            e.printStackTrace();
            return uuid;
        }
        return uuid;
    }

    @RequestMapping(value = "/user/validateCode/{tokenUuid}")
    public String getVerifyCode(@PathVariable String tokenUuid) throws IOException {
        String randomStr = null;
        logger.info("======> Select key =" + tokenUuid);
        try {
            String uuid = redisService.getByKey(tokenUuid);
            logger.info("======>Get value = " + uuid + " by key =" + tokenUuid);
            if (StringUtils.isEmpty(uuid)) {
                return uuid;
            }
            randomStr = ImageUtil.getRandomStr();
            redisService.del(tokenUuid);
            logger.info("======> Deleted key = " + uuid);
            redisService.set(tokenUuid, randomStr);
            logger.info("======> Set key = " + uuid + " value = " + randomStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return randomStr;
    }

    @RequestMapping(value = "/user/findByUserCondition", method = RequestMethod.POST)
    public User checkUserName(@RequestBody User user) {
        logger.info("======>findByUserCondition =" + user.toString());
        User byUserName = userService.findByUserCondition(user);
        return byUserName;
    }

    @RequestMapping(value = "/user/validatePhone/{phone}")
    public Boolean checkPhoneNumber(@PathVariable String phone) {
        Boolean flag = false;
        User user = new User();
        user.setPhone(phone);
        logger.info("======>CheckPhoneNumber phoneNumber= " + phone);
        User u = userService.findByUserCondition(user);
        if (u == null) {
            flag = true;
            logger.info("======>CheckPhoneNumber result is " + flag);
        }
        return flag;
    }

    @RequestMapping(value = "/user/codeValidate/{signUuid}")
    public String checkCode(@PathVariable String signUuid) {

        logger.info("======> Get by key = " + signUuid);

        String value = redisService.getByKey(signUuid);
        logger.info("======> Get value= " + value);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return value;
    }


    @RequestMapping(value = "/user/generateUserToken/{username}")
    public String generateUserToken(@PathVariable String username) {

        try {
            // 生成令牌
            String token = TokenUtil.generateUserToken(username);
            User user = new User();
            user.setUsername(username);
            // 根据用户名获取用户
            user = userService.findByUserCondition(user);
            // 将用户信息存储到map中。
            Map<String, Object> tokenMap = new HashMap<String, Object>();
            tokenMap.put("id", user.getId());
            tokenMap.put("userName", user.getUsername());
            tokenMap.put("phone", user.getPhone());
            tokenMap.put("userType", user.getUserType());
            tokenMap.put("payPwdStatus", user.getPayPwdStatus());
            tokenMap.put("emailStatus", user.getEmailStatus());
            tokenMap.put("realName", user.getRealName());
            tokenMap.put("identity", user.getIdentity());
            tokenMap.put("realNameStatus", user.getRealNameStatus());
            tokenMap.put("payPhoneStatus", user.getPhoneStatus());
            redisService.del(token);
            boolean hmset = redisService.hmset(token, tokenMap);// 将信息存储到redis中
            logger.info("======> Save token key=" + token + "  value=" + tokenMap.toString());
// 获取配置文件中用户的生命周期，如果没有，默认是30分钟
            redisService.expire(token, 30 * 60);
            if (!hmset) {
                return null;
            }
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("token", e);
            return null;
        }
    }


    @RequestMapping(value = "/user/getTokenFromRedis/{token:.+}", method = RequestMethod.GET)
    public Map<String, Object> getRedisValueByKey(@PathVariable String token) {
        boolean exists = redisService.exists(token);
        logger.info("======> Get token key=" + token);
        Map<String, Object> map = (Map) redisService.hmget(token);
        logger.info("======> Get value=" + map.toString() + "  by token=" + token);
        return map;
    }

    @RequestMapping(value = "/user/redisDelToken/{token:.+}", method = RequestMethod.GET)
    public Boolean getRedisDel(@PathVariable String token) {
        redisService.del(token);
        Boolean hmget = redisService.exists(token);
        if (!hmget) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public User register(@RequestBody User user) {
        user.setPassword(MD5Util.md5(user.getUsername() + user.getPhone()));
        userService.add(user);
        return user;
    }


    @RequestMapping(value = "/user/addUserAcount", method = RequestMethod.POST)
    public Boolean addUserAcount(@RequestBody UserAcount userAcount) {
        return userAcountService.add(userAcount);
    }


    @RequestMapping(value = "/user/modifyUser", method = RequestMethod.POST)
    public Boolean modifyUser(@RequestBody User user) {
        return userService.update(user);
    }

    @RequestMapping(value = "/user/getUserById/{id}", method = RequestMethod.GET)
    public User getUserById(@PathVariable Integer id) {
        return userService.findById(id);
    }

    @RequestMapping("/account/accountHomepage/{userId}")
    public UserAcount getUserAccountByUserId(@PathVariable Integer userId) {
        UserAcount userAcount = new UserAcount();
        userAcount.setUserId(userId);
        return userAcountService.findUserAcountByUserId(userAcount);

    }
    @RequestMapping(value = "/account/modifyUserAcount",method = RequestMethod.POST)
    public Boolean modifyUserAcount(@RequestBody UserAcount userAcount) {
        return userAcountService.modify(userAcount);
    }

}
